package com.ideaaedi.commonspring.aop;

import com.ideaaedi.commonspring.lite.antidupli.AntiDuplication;
import com.ideaaedi.commonspring.spi.AntiDuplicateExecutor;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.core.Ordered;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * {@link AntiDuplication}aop实现
 *
 * @author <font size = "20" color = "#3CAA3C"><a href="https://gitee.com/JustryDeng">JustryDeng</a></font> <img
 * src="https://gitee.com/JustryDeng/shared-files/raw/master/JustryDeng/avatar.jpg" />
 * @since 2100.7.3
 */
public class AntiDuplicationAdvice implements MethodInterceptor, Ordered {
    
    @SuppressWarnings("rawtypes")
    private final AntiDuplicateExecutor antiDuplicateExecutor;
    
    public AntiDuplicationAdvice(@SuppressWarnings("rawtypes") AntiDuplicateExecutor antiDuplicateExecutor) {
        this.antiDuplicateExecutor = antiDuplicateExecutor;
    }
    
    @Override
    public int getOrder() {
        return antiDuplicateExecutor.adviceOrder();
    }
    
    @Nullable
    @Override
    public Object invoke(@Nonnull MethodInvocation invocation) throws Throwable {
        Object execResult = null;
        Object targetPointResult = null;
        Throwable throwable = null;
        try {
            execResult = antiDuplicateExecutor.exec(invocation);
            targetPointResult = invocation.proceed();
        } catch (Throwable th){
            throwable = th;
            throw th;
        } finally {
            //noinspection unchecked
            antiDuplicateExecutor.doFinally(throwable, execResult, targetPointResult);
        }
        return targetPointResult;
    }
}
